#include "LoginSvr.h"
#include "sol/sol.hpp"
#include "db_driver/db_driver.h"

using namespace su;
using namespace std;
using namespace proto;

LoginSvr& gLoginSvr = LoginSvr::Ins();

bool LoginSvr::OnStart()
{
	L_COND_F(m_cfg.Init());

	LDEBUG("listen addr port:", m_cfg.port, "ip:", m_cfg.ip);
	bool r = m_clientListener.Init(m_cfg.port, m_cfg.ip.c_str());
	L_COND_F(r);

	LDEBUG("dbproxy addr", m_cfg.dbproxyIp, ":", m_cfg.dbproxyPort);
	Dbproxy::Ins().Init(m_cfg.dbproxyIp, m_cfg.dbproxyPort, []() { 
		LDEBUG("con dbproxy ok"); 
		gLoginSvr.SetReady(ReadyType::DB_CON);
	});
	return true;
}

void LoginSvr::SetReady(ReadyType flag)
{
	m_readySet[(int)flag] = true;
	if (m_readySet.all())
	{
		FireEvent<EVENTID::SVR_READY>();
		LDEBUG("===============================login start ok===============================\n");
	}
}

proto::AccAddr LoginSvr::GetBlanceAcc()
{
	//简单轮询实现负载均衡
	m_accIdx++;
	m_accIdx %= m_cfg.vecAcc.size();
	return m_cfg.vecAcc[m_accIdx];
}

bool LoginCfg::Init()
{
	sol::state lua;
	lua.open_libraries(sol::lib::base,
		sol::lib::package,
		sol::lib::table,
		sol::lib::string);

	sol::protected_function_result r = lua.do_file("login.lua");
	if (!r.valid())
	{
		sol::error err = r;
		std::string what = err.what();
		LERROR("zone.lua load fail error:", what);
		return false;
	}
	svrId       = lua["svrId"];
	dbproxyIp   = lua["dbproxyIp"];
	dbproxyPort = lua["dbproxyPort"]; 
	port        = lua["port"];
	ip          = lua["ip"];

	size_t accessNum = lua["accessNum"];
	LDEBUG("accessNum", accessNum);
	for (size_t i = 0; i < accessNum ; i++)
	{
		AccAddr v;
		v.port = lua["access"][i+1]["exPort"];
		v.ip   = lua["access"][i + 1]["exIp"];
		vecAcc.push_back(v);
	}
	L_COND_F(SvrId2Type(svrId) == SvrType::Login, "svrId=", svrId);
	return true;
}

